/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.data;

import java.util.List;

import net.datajanitor.baja.spi.data.FileInfoTree;

/**
 * Represents an existing file or directory in a Box account. 
 */
public class FileInfo {
    private final int id;
    private final String name;
    private final boolean isDir;
    private final FileInfoTree tree;
           
    public static interface Visitor {
        public void visit(FileInfo file);
    }
      
    public FileInfo(int id, String name, boolean isDir, FileInfoTree tree) {
        this.id = id;
        this.name = name;
        this.isDir = isDir;       
        this.tree = tree;        
    }
      
    public FileInfo getParent() {
        return this.tree.getParent(this);
    }
     
    public int getId() {
        return this.id;
    }
    
    public String getName() {
        return this.name;    
    }
    
    public boolean isFile() {
        return !this.isDir;    
    }
    
    public boolean isDirectory() {
        return this.isDir;    
    }
    
    public boolean isRootDirectory() {
        return getParent() == null;
    }
    
    public String getPath() {
        StringBuilder path = new StringBuilder();
        FileInfo parent = getParent();
        if (parent != null) {
            path.append(parent.getPath()).append(this.name);
        }
        
        if (this.isDir) {
            path.append("/");
        }
        
        return path.toString();
    }
    
    public List<FileInfo> getChildren() {
        return this.tree.getChildren(this);    
    }
    
    public FileInfo addChild(int id, String fileName, boolean isDir) {
        FileInfo child = new FileInfo(id, fileName, isDir, this.tree);
        tree.addFileInfo(this, child);
        
        return child;
    }
    
    public void accept(Visitor visitor) {
        this.tree.acceptAt(this, visitor);
    }
    
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(getClass().getName()).append("[id=").append(getId()).append(",parent=")
               .append(getParent().getPath()).append(",name=").append(getName())
               .append(",isDir=").append(isDir).append("]");
        
        return builder.toString();
    }
}
